<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="班级名称">
      <el-input v-model="form.class_name" />
    </el-form-item>
    <el-form-item label="所属专业">
      <el-select v-model="form.major_name" @change="getMajorInfo">
        <el-option v-for="cls in majors" :key="cls.major_name" :label="cls.major_name" :value="cls.major_name"/>
      </el-select>
    </el-form-item>

    <el-form-item label="所属学院">
      <el-input v-model="form.department_name" disabled/>
    </el-form-item>
    <el-form-item label="年级">
      <el-input v-model="form.grade" />
    </el-form-item>
    <el-form-item label="学生人数">
      <el-input v-model="form.class_p_number" disabled/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm() ">确认修改</el-button>
      <el-button @click="closeDialog() ">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import ClassApi from '@/api/ClassApi';

export default {
  props: {
    currentClass: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        class_name: '',
        major_name: '',
        department_name: '',
        grade: '',
        class_p_number: '',
        major_id:'',
      },
      majors: []// 专业列表

    };
  },
  methods: {
    submitForm() {
      this.$emit('submit-form',this.form);
    },
    closeDialog() {
      this.$emit('close-dialog');
    },
    getMajorInfo(major_id) {
      this.initialMajor_Id_change= false; // 标记为已修改
      const selectedMajor = this.majors.find(cls => cls.major_id === major_id);
      if (selectedMajor) {
        this.form.department_name = selectedMajor.college_name;
      }
    },
    async fetchMajors() {
      try {
        ClassApi.getMajorsForm().then(res => {
          if (res.data.code === 200) {
            this.majors = res.data.data ||res.data;
          } else {
            this.$message.error('获取专业信息失败');
          }
        });
      } catch (error) {
        console.error("专业信息获取错误:", error);
        this.$message.error('获取专业信息失败');
      }
    }
  },
  watch: {
    // 监听父组件传入的currentStudent变化
    currentClass: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          // 将父组件传入的班级数据填充到表单中
          this.form = {
            class_name: newVal.class_name,
            major_name: newVal.major_name,
            department_name: newVal.college_name,
            grade: newVal.grade,
            class_p_number: newVal.class_p_number,
          }
        }
      }
    }
  },
  created() {
    this.fetchMajors();
  }
};
</script>
